package com.agileai.wm.module.workmanage.handler;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import com.agileai.common.KeyGenerator;
import com.agileai.domain.DataParam;
import com.agileai.domain.DataRow;
import com.agileai.hotweb.annotation.PageAction;
import com.agileai.hotweb.bizmoduler.core.MasterSubService;
import com.agileai.hotweb.controller.core.MasterSubEditMainHandler;
import com.agileai.hotweb.domain.FormSelect;
import com.agileai.hotweb.domain.FormSelectFactory;
import com.agileai.hotweb.domain.core.User;
import com.agileai.hotweb.renders.AjaxRenderer;
import com.agileai.hotweb.renders.LocalRenderer;
import com.agileai.hotweb.renders.ViewRenderer;
import com.agileai.util.ListUtil;
import com.agileai.util.StringUtil;
import com.agileai.wm.cxmodule.WmWeekManage;

public class WmWeekManageEditHandler
        extends MasterSubEditMainHandler {
    public WmWeekManageEditHandler() {
        super();
        this.listHandlerClass = WmWeekManageListHandler.class;
        this.serviceId = buildServiceId(WmWeekManage.class);
        this.baseTablePK = "WW_ID";
        this.defaultTabId = "WmWeekentry";
    }
    
	public ViewRenderer prepareDisplay(DataParam param) {
		String operaType = param.get(OperaType.KEY);
		String canEdit ="false";
		User user = (User)this.getUser();
		setAttribute("EMP_ID",param.get("EMP_ID"));
		setAttribute("EMP_JOB",param.get("EMP_JOB"));
		DataRow record = null;
		if (isReqRecordOperaType(operaType)){
			String WW_ID=param.getString("WW_ID");
			if (StringUtil.isNullOrEmpty(WW_ID)){
				String currentSubTableId = param.get("currentSubTableId");
				if(currentSubTableId==null){
					currentSubTableId="WmWeekentry";
				}
				List<DataRow> WmWeekentry = new ArrayList<DataRow>();
				List<DataRow> WmPrepare = new ArrayList<DataRow>();
				setAttribute("WmWeekentryRecords", WmWeekentry);
				setAttribute("WmPrepareRecords", WmPrepare);
				setAttribute("currentSubTableId",currentSubTableId);
				setAttribute("currentSubTableIndex", getTabIndex(getAttributeValue("currentSubTableId")));
				setAttribute("STATE", "Audit");
				return new LocalRenderer(getPage());
			}else{
				record = getService().getMasterRecord(param);
				this.setAttributes(record);	
			}
			canEdit="true";
		}
		
		if(null != record){
			if("INITIALISE".equals(record.getString("WW_STATE"))){
				this.setAttribute("showBtn", true);
			}
		}
		
		if(OperaType.CREATE.equals(operaType)){
			setAttribute("extraction", false);
			setAttribute("confirmed", false);
		}
		
		String userId = user.getUserId();
		String currentUserId = null;
		if(null == record || "null".equals(record)){
			currentUserId = userId;
		}else{
			currentUserId = record.getString("USER_ID");
		}
		
		if("Audit".equals(param.get("STATE"))){
			setAttribute("STATE", "Audit");
		}
		else{
			setAttribute("STATE", "USER");
		}
		List<DataRow> groupRecords = getService().getGroupRecords(currentUserId);
		String grpId = param.get("grpId");
		if(groupRecords != null && groupRecords.size() > 0){
			if (StringUtil.isNullOrEmpty(grpId)){
				DataRow row = groupRecords.get(0);
				grpId = row.getString("GRP_ID");
			}
			FormSelect grpFormSelect = new FormSelect();
			grpFormSelect.setKeyColumnName("GRP_ID");
			grpFormSelect.setValueColumnName("GRP_NAME");
			grpFormSelect.putValues(groupRecords);
			grpFormSelect.setSelectedValue(grpId);
			this.setAttribute("grpId", grpFormSelect);
		}
		
		String currentSubTableId = param.get("currentSubTableId",defaultTabId);
		if (!currentSubTableId.equals(MasterSubService.BASE_TABLE_ID)){
			String subRecordsKey = currentSubTableId + "Records";
			if (!this.getAttributesContainer().containsKey(subRecordsKey)){
				List<DataRow> subRecords = getService().findSubRecords(currentSubTableId, param);
				this.setAttribute(currentSubTableId+"Records", subRecords);
			}
		}
		
		List<DataRow> empDateRowList = getService().getEmpJobRecords(userId, grpId);
		for(int i =0;i<empDateRowList.size();i++){
			DataRow empRow = empDateRowList.get(i);
			String empJob = empRow.getString("EMP_JOB");
			if("Master".equals(empJob) ||"Auditer".equals(empJob)){
				this.setAttribute("empJobShow", "empJobShow");
			}
		}
		
		String wwState = param.getString("WW_STATE");
		String tabUserId = param.get("USER_ID");
		if("CONFIRMED".equals(wwState) && tabUserId.equals(userId) ){
			this.setAttribute("empJobShow", false);
		}else if("CONFIRMED".equals(wwState) && tabUserId != userId){
			this.setAttribute("empJobShow", true);
		}else if("INITIALISE".equals(wwState)){
			this.setAttribute("empJobShow", true);
		}
		
		
		String wwId = param.getString("WW_ID");
		if("" == wwId || null == wwId || "null".equals(wwId)){
			this.setAttribute("ExtractShow", true);
		}
		
		this.setAttribute("userId",userId);	
		this.setAttribute("canEdit",canEdit);	
		this.setAttribute("currentSubTableId", currentSubTableId);
		this.setAttribute("currentSubTableIndex", getTabIndex(currentSubTableId));
		String operateType = param.get(OperaType.KEY);
		this.setOperaType(operateType);
		processPageAttributes(param);
		return new LocalRenderer(getPage());
	}

    protected void processPageAttributes(DataParam param) {
    	String userId = getAttributeValue("USER_ID");
        if (StringUtil.isNullOrEmpty(userId)){
        	User user = (User)this.getUser();
        	setAttribute("USER_ID", user.getUserId());
        }
    	
    	setAttribute("ENTRY_STATESelect",FormSelectFactory.create("ENTRY_STATE"));
        setAttribute("WORK_FINISHSelect",FormSelectFactory.create("WORK_FINISH"));
        
        setAttribute("ENTRY_STATE",
                FormSelectFactory.create("ENTRY_STATE")
                       .addSelectedValue(getOperaAttributeValue("ENTRY_STATE","")));
        setAttribute("WW_STATE",
                FormSelectFactory.create("WEEK_WORK_STATE")
                    .addSelectedValue(getOperaAttributeValue("WW_STATE","INITIALISE")));
        setAttribute("WW_COMPLETION",
                FormSelectFactory.create("WORK_FINISH_VALUE")
                    .addSelectedValue(getOperaAttributeValue("WW_COMPLETION","0")));
     }
    
    protected String[] getEntryEditFields(String currentSubTableId) {
        List<String> temp = new ArrayList<String>();
        if ("WmWeekentry".equals(currentSubTableId)) {
            temp.add("ENTRY_ID");
            temp.add("WW_ID");
            temp.add("ENTRY_DESCRIBE");
            temp.add("ENTRY_DAY");
            temp.add("ENTRY_PLAN");
            temp.add("ENTRY_REALITY");
            temp.add("ENTRY_FINISH");
            temp.add("ENTRY_GROUP");
            temp.add("ENTRY_STATE");
            temp.add("ENTRY_SORT");
        }
        if ("WmPrepare".equals(currentSubTableId)) {
            temp.add("PRE_ID");
            temp.add("WW_ID");
            temp.add("PRE_DESCRIBE");
            temp.add("PRE_LOAD");
            temp.add("PRE_SORT");
        }
        return temp.toArray(new String[] {  });
    }

	public ViewRenderer doAddEntryRecordAction(DataParam param){
		String currentSubTableId = param.get("currentSubTableId");
		int currentRecordSize = param.getInt("currentRecordSize");
		List<DataRow> subRecords = new ArrayList<DataRow>();
		String[] entryEditFields = this.getEntryEditFields(currentSubTableId);
		for (int i=0;i < currentRecordSize;i++){
			DataRow row = new DataRow();
			for (int j=0; j < entryEditFields.length;j++){
				String field = entryEditFields[j];
				row.put(field,param.get(field+"_"+i));
			}
			row.put("_state",param.get("state_"+i));
			subRecords.add(row);
		}
		String foreignKey = this.getEntryEditForeignKey(currentSubTableId);
		DataRow addRow = new DataRow();
		if ("WmWeekentry".equals(currentSubTableId)) {
			addRow.put("_state","insert",foreignKey,param.get(baseTablePK),"ENTRY_STATE","0","ENTRY_FINISH","0");
			addRow.put("ENTRY_PLAN","1");
		}
		if ("WmPrepare".equals(currentSubTableId)) {
			addRow.put("_state","insert",foreignKey,param.get(baseTablePK),"PRE_LOAD","1");
		}
        subRecords.add(addRow);
		String subRecordsKey = currentSubTableId + "Records";
		this.setAttribute(subRecordsKey, subRecords);
		return prepareDisplay(param); 
	}
	
	public ViewRenderer doGetEntryPrepareRecordAction(DataParam param) {
		String wtId = param.get("WT_ID");
		String wwId = param.get("WW_ID");
		User user = (User) this.getUser();
		String userId = user.getUserId();
		DataRow row = getService().getBeforeWeekRow(wtId);
		if (row != null && row.size() > 0) {
			String wtIdBefore = row.getString("WT_ID");
			List<DataRow> beforeWeekWorks = getService().findNofinishWeeks(
					wtIdBefore, userId);
			KeyGenerator keyGenerator = KeyGenerator.instance();
			if (beforeWeekWorks != null && beforeWeekWorks.size() > 0) {
				DataRow maxEntrySort=getService().findMaxEntrySort(wwId);
			  	int maxNumber=maxEntrySort.getInt("max(ENTRY_SORT)");
				List<DataParam> entryParamList = ListUtil.toParamList(beforeWeekWorks);
				for (int i=0;i < entryParamList.size();i++){
					DataParam enDataParam = entryParamList.get(i);
					enDataParam.put("ENTRY_ID",keyGenerator.genKey());
					enDataParam.put("WW_ID",wwId);
					enDataParam.put("ENTRY_SORT",++maxNumber);
					enDataParam.put("ENTRY_STATE","0","ENTRY_FINISH","0");
					
				}
				getService().insertWWEntryParam(entryParamList);
			}

			List<DataRow> preBeforeWeekWorks = getService()
					.findLastWeekPresRecord(wtIdBefore, userId);
			if (preBeforeWeekWorks != null && preBeforeWeekWorks.size() > 0) {
				List<DataParam> preParamList = ListUtil.toParamList(preBeforeWeekWorks);
			    DataRow maxPreSort=getService().findMaxPreSort(wwId);
			    int maxNumber=maxPreSort.getInt("max(PRE_SORT)");
				for (int i=0;i < preParamList.size();i++){
					DataParam enDataParam = preParamList.get(i);
					enDataParam.put("PRE_ID",keyGenerator.genKey());
					enDataParam.put("WW_ID",wwId);
					enDataParam.put("PRE_SORT",++maxNumber);
				}
				getService().insertWWPrepareParam(preParamList);
			}
		} else {
			this.setErrorMsg("这是第一条周报记录,上周记录不存在 !!!");
		}
		return prepareDisplay(param);
	}
	  
	  
	  public ViewRenderer doSaveMasterRecordAction(DataParam param){
			String operateType = param.get(OperaType.KEY);
			String responseText = "fail";
			if (OperaType.CREATE.equals(operateType)){
				List<DataRow> checkTime=getService().checkWeekTime(param);
				if(checkTime.size()==0){
					getService().createMasterRecord(param);
					responseText = param.get(baseTablePK);
				}
			}
			else if(OperaType.UPDATE.equals(operateType)){
				getService().updateMasterRecord(param);
				saveSubRecords(param);
				responseText = param.get(baseTablePK);
			}
			return new AjaxRenderer(responseText);
		}
	  
	  public ViewRenderer doConvertEntryRecordAction(DataParam param){
			String currentSubTableId = param.get("currentSubTableId");
			int currentRecordIndex = param.getInt("currentRecordIndex");
			String state = param.get("state_"+currentRecordIndex);
			String preId=param.get("PRE_ID_"+currentRecordIndex);
			String wwId=param.get("WW_ID_"+currentRecordIndex);
			List<DataRow> newEntry=getService().findWeekWorkPres(preId);
			DataRow maxSort=getService().findMaxEntrySort(wwId);
			int maxNumber=maxSort.getInt("max(ENTRY_SORT)");
			int entrySort=maxNumber+1;
			newEntry.get(0).put("ENTRY_ID", preId);
			newEntry.get(0).put("WW_ID", wwId);
			newEntry.get(0).put("ENTRY_STATE","0");
			newEntry.get(0).put("ENTRY_FINISH","0");
			newEntry.get(0).put("ENTRY_SORT",entrySort);
			getService().insertWeekWorkEntry(newEntry);
			int currentRecordSize = param.getInt("currentRecordSize");
			List<DataRow> subRecords = new ArrayList<DataRow>();
			String[] entryEditFields = this.getEntryEditFields(currentSubTableId);
			for (int i=0;i < currentRecordSize;i++){
				if (i == currentRecordIndex)continue;
				DataRow row = new DataRow();
				for (int j=0; j < entryEditFields.length;j++){
					String field = entryEditFields[j];
					row.put(field,param.get(field+"_"+i));
				}
				row.put("_state",param.get("state_"+i));
				subRecords.add(row);
			}
			String subRecordsKey = currentSubTableId + "Records";
			this.setAttribute(subRecordsKey, subRecords);
			if (!state.equals("insert")){
				DataParam deleteParam = new DataParam();
				String pKField = getEntryEditTablePK(currentSubTableId);
				deleteParam.put(pKField,param.get(pKField+"_"+currentRecordIndex));
				getService().deleteSubRecord(currentSubTableId, deleteParam);
			}
			return prepareDisplay(param);		
		}
	  
	  public ViewRenderer doConvertPreRecordAction(DataParam param){
			String currentSubTableId = param.get("currentSubTableId");
			int currentRecordIndex = param.getInt("currentRecordIndex");
			String state = param.get("state_"+currentRecordIndex);
			String entryId=param.get("ENTRY_ID_"+currentRecordIndex);
			String wwId=param.get("WW_ID_"+currentRecordIndex);
			List<DataRow> newEntry=getService().findWeekWorkEntry(entryId);
			DataRow maxSort=getService().findMaxPreSort(wwId);
			int maxNumber=maxSort.getInt("max(PRE_SORT)");
			int entrySort=maxNumber+1;
			newEntry.get(0).put("PRE_ID", entryId);
			newEntry.get(0).put("WW_ID", wwId);
			newEntry.get(0).put("PRE_DESCRIBE",param.get("ENTRY_DESCRIBE_"+currentRecordIndex));
			newEntry.get(0).put("PRE_LOAD",param.get("ENTRY_PLAN_"+currentRecordIndex));
			newEntry.get(0).put("PRE_SORT",entrySort);
			getService().insertWeekWorkPrepare(newEntry);
			int currentRecordSize = param.getInt("currentRecordSize");
			List<DataRow> subRecords = new ArrayList<DataRow>();
			String[] entryEditFields = this.getEntryEditFields(currentSubTableId);
			for (int i=0;i < currentRecordSize;i++){
				if (i == currentRecordIndex)continue;
				DataRow row = new DataRow();
				for (int j=0; j < entryEditFields.length;j++){
					String field = entryEditFields[j];
					row.put(field,param.get(field+"_"+i));
				}
				row.put("_state",param.get("state_"+i));
				subRecords.add(row);
			}
			String subRecordsKey = currentSubTableId + "Records";
			this.setAttribute(subRecordsKey, subRecords);
			if (!state.equals("insert")){
				DataParam deleteParam = new DataParam();
				String pKField = getEntryEditTablePK(currentSubTableId);
				deleteParam.put(pKField,param.get(pKField+"_"+currentRecordIndex));
				getService().deleteSubRecord(currentSubTableId, deleteParam);
			}
			return prepareDisplay(param);		
		}
	
    protected String getEntryEditTablePK(String currentSubTableId) {
        HashMap<String, String> primaryKeys = new HashMap<String, String>();
        primaryKeys.put("WmWeekentry", "ENTRY_ID");
        primaryKeys.put("WmPrepare", "PRE_ID");
        return primaryKeys.get(currentSubTableId);
    }

    protected String getEntryEditForeignKey(String currentSubTableId) {
        HashMap<String, String> foreignKeys = new HashMap<String, String>();
        foreignKeys.put("WmWeekentry", "WW_ID");
        foreignKeys.put("WmPrepare", "WW_ID");
        return foreignKeys.get(currentSubTableId);
    }
    
    @PageAction
	public ViewRenderer confirmed(DataParam param){
    	param.put("WW_STATE", "CONFIRMED");
    	param.put("ENTRY_STATE", "1");
    	getService().updateStateRecord(param);
    	getService().updateEntryState(param);
    	return prepareDisplay(param);
	}
    @PageAction
    public ViewRenderer summary(DataParam param){
    	param.put("WW_STATE", "SUMMARY");
    	param.put("ENTRY_STATE", "1");
    	getService().updateEntryState(param);
    	getService().updateStateRecord(param);
    	return prepareDisplay(param);
    }
    @PageAction
    public ViewRenderer sealed(DataParam param){
    	param.put("WW_STATE", "SAVE");
    	param.put("ENTRY_STATE", "1");
    	getService().updateEntryState(param);
    	getService().updateStateRecord(param);
    	return prepareDisplay(param);
    }
	
    public ViewRenderer doMoveUpAction(DataParam param){
		String currentSubTableId = param.get("currentSubTableId");
		boolean isFirst = getService().isFirstChild(currentSubTableId,param);
		
		String currentRecordIndex = param.get("currentRecordIndex");
		String entryId = null;
		if("WmWeekentry".equals(currentSubTableId)){
			 entryId = "ENTRY_ID_"+currentRecordIndex;
		}else if("WmPrepare".equals(currentSubTableId)){
			entryId = "PRE_ID_"+currentRecordIndex;
		}
		String entryIdValue = param.get(entryId);
		if(null == entryIdValue || "".equals(entryIdValue)){
			String wwId=param.get("WW_ID_"+currentRecordIndex);
			List<DataRow> newEntryList = new ArrayList<DataRow>();
			DataRow newEntryRow = new DataRow();
			String entryIdUuid = KeyGenerator.instance().genKey();
			if("WmWeekentry".equals(currentSubTableId)){
				DataRow maxSort=getService().findMaxEntrySort(wwId);
				int maxNumber=maxSort.getInt("max(ENTRY_SORT)");
				int entrySort=maxNumber+1;
				newEntryRow.put("ENTRY_ID", entryIdUuid);
				newEntryRow.put("WW_ID", wwId);
				newEntryRow.put("ENTRY_DESCRIBE", param.get("ENTRY_DESCRIBE_"+currentRecordIndex));
				newEntryRow.put("ENTRY_PLAN", param.get("ENTRY_PLAN_"+currentRecordIndex));
				newEntryRow.put("ENTRY_FINISH","0");
				newEntryRow.put("ENTRY_GROUP",param.get("ENTRY_GROUP_"+currentRecordIndex));
				newEntryRow.put("ENTRY_STATE","0");
				newEntryRow.put("ENTRY_SORT",entrySort);
				newEntryList.add(newEntryRow);
				param.put(entryId,entryIdUuid);
				getService().insertWeekWorkEntryParam(newEntryList);
			}else if("WmPrepare".equals(currentSubTableId)){
				DataRow maxSort=getService().findMaxPreSort(wwId);
				int maxNumber=maxSort.getInt("max(PRE_SORT)");
				int entrySort=maxNumber+1;
				newEntryRow.put("PRE_ID", entryIdUuid);
				newEntryRow.put("WW_ID", wwId);
				newEntryRow.put("PRE_DESCRIBE", param.get("PRE_DESCRIBE_"+currentRecordIndex));
				newEntryRow.put("PRE_LOAD",param.get("PRE_LOAD_"+currentRecordIndex));
				newEntryRow.put("PRE_SORT",entrySort);
				newEntryList.add(newEntryRow);
				param.put(entryId,entryIdUuid);
				getService().insertWeekWorkPrepareParam(newEntryList);
			}
		
		}
		this.setAttribute("currentRecordIndex", currentRecordIndex);
		if (isFirst){
			setErrorMsg(this.moveUpErrorMsg);
		}else{
			getService().changeCurrentSort(param, true);
		}
		return prepareDisplay(param);
	}
    
    public ViewRenderer doMoveDownAction(DataParam param){
		String currentSubTableId = param.get("currentSubTableId");
		String currentRecordIndex = param.get("currentRecordIndex");
		String entryId = null;
		if("WmWeekentry".equals(currentSubTableId)){
			 entryId = "ENTRY_ID_"+currentRecordIndex;
		}else if("WmPrepare".equals(currentSubTableId)){
			entryId = "PRE_ID_"+currentRecordIndex;
		}
		String entryIdValue = param.get(entryId);
		if(null == entryIdValue || "".equals(entryIdValue)){
			String wwId=param.get("WW_ID_"+currentRecordIndex);
			List<DataRow> newEntryList = new ArrayList<DataRow>();
			DataRow newEntryRow = new DataRow();
			String entryIdUuid = KeyGenerator.instance().genKey();
			if("WmWeekentry".equals(currentSubTableId)){
				DataRow maxSort=getService().findMaxEntrySort(wwId);
				int maxNumber=maxSort.getInt("max(ENTRY_SORT)");
				int entrySort=maxNumber+1;
				newEntryRow.put("ENTRY_ID", entryIdUuid);
				newEntryRow.put("WW_ID", wwId);
				newEntryRow.put("ENTRY_DESCRIBE", param.get("ENTRY_DESCRIBE_"+currentRecordIndex));
				newEntryRow.put("ENTRY_PLAN", param.get("ENTRY_PLAN_"+currentRecordIndex));
				newEntryRow.put("ENTRY_FINISH","0");
				newEntryRow.put("ENTRY_GROUP",param.get("ENTRY_GROUP_"+currentRecordIndex));
				newEntryRow.put("ENTRY_STATE","0");
				newEntryRow.put("ENTRY_SORT",entrySort);
				newEntryList.add(newEntryRow);
				param.put(entryId,entryIdUuid);
				getService().insertWeekWorkEntryParam(newEntryList);
			}else if("WmPrepare".equals(currentSubTableId)){
				DataRow maxSort=getService().findMaxPreSort(wwId);
				int maxNumber=maxSort.getInt("max(PRE_SORT)");
				int entrySort=maxNumber+1;
				newEntryRow.put("PRE_ID", entryIdUuid);
				newEntryRow.put("WW_ID", wwId);
				newEntryRow.put("PRE_DESCRIBE", param.get("PRE_DESCRIBE_"+currentRecordIndex));
				newEntryRow.put("PRE_LOAD",param.get("PRE_LOAD_"+currentRecordIndex));
				newEntryRow.put("PRE_SORT",entrySort);
				newEntryList.add(newEntryRow);
				param.put(entryId,entryIdUuid);
				getService().insertWeekWorkPrepareParam(newEntryList);
			}
		}
		boolean isLast = getService().isLastChild(currentSubTableId,param);
		int currentRecordIndexNum = Integer.valueOf(currentRecordIndex);
		currentRecordIndexNum = currentRecordIndexNum + 2;
		String currentRecordIndexStr = String.valueOf(currentRecordIndexNum);
		this.setAttribute("currentRecordIndex", currentRecordIndexStr);
		
		if (isLast){
			setErrorMsg(this.moveDownErrorMsg);
		}else{
			getService().changeCurrentSort(param, false);
		}		
		return prepareDisplay(param);
	}	

    protected WmWeekManage getService() {
        return (WmWeekManage) this.lookupService(this.getServiceId());
    }
}
